//
//  DeviceInfo.swift
//  DaRings
//
//  Created by 尹琼 on 2022/11/25.
//

import UIKit
import HandyJSON
import CRPSmartRing

/// 本类保存最近的连接设备信息
public class DeviceInfo: NSObject, HandyJSON {
    
    /// uuid
    public var uuid: String?
    
    /// mac地址
    public var adress: String?
    
    /// 设备国际化名称
    public var localName: String?
    
    /// 版本号
    public var versoin: String?
    
    /// 序列号
    public var gitHash: String?
    
    public var RSSI: Int = 0
    
    
    /// 是否隐藏
    public var hide: Int = 0
    
    /// 设备支持的运动类型
    public var trainingTypes: [TrainingType]? {
        
        didSet {
            
            if trainingTypes?.isEmpty == true {
                trainingTypes = nil
            }
            
        }
        
    }
    
    /// 设备尺寸颜色类型信息
    public var info: RingInfo? {
        
        guard let adress = adress else {
            return nil
        }
        return RingInfo.current(adress: adress)
        
    }
    
    /// 是否移除绑定
    public var isBind = false
    
    /// 是否是首次连接
    public var isFirstConnect = true
    
    /// 是否是空数据
    public var isEmpty: Bool {
        
        guard let dict = UserDefaults.standard.dictionary(forKey: DeviceInfo.userDefaultKey) else {
            return true
        }
        
        return dict.isEmpty
    
    }
    
    public required override init() {}
    

}

extension DeviceInfo {
    
    private static let userDefaultKey = "DeviceInfo"
    
    /// 当前存储的设备信息
    /// - Returns: model
    public static func current() ->DeviceInfo {
        
        let dict = UserDefaults.standard.dictionary(forKey: DeviceInfo.userDefaultKey)
        
        guard let deviceInfo = DeviceInfo.deserialize(from: dict) else {
            
            let deviceInfo = DeviceInfo()
            
            return deviceInfo
        }
        
        return deviceInfo
        
    }
    
    /// 保存信息
    public func save() {
        
        guard var dict = self.toJSON() else {
            UserDefaults.standard.removeObject(forKey: DeviceInfo.userDefaultKey)
            return
            
        }
        
        if let old = Self.current().toJSON() {
            
            old.forEach { key, value in
                
                if !dict.keys.contains(key) {
                    dict[key] = value
                }
            }
        }
        
        if dict.isEmpty {
            UserDefaults.standard.removeObject(forKey: DeviceInfo.userDefaultKey)
        } else {
            
            UserDefaults.standard.set(dict, forKey: DeviceInfo.userDefaultKey)
        }
    }
    
    
    /// 从连接后得到的信息中保存
    /// - Parameter discovery: SDK 返回
    public func save(of discovery: CRPSmartRing.CRPDiscovery?) {
        
        if let discovery = discovery {
            let peripheral = discovery.remotePeripheral
            
            uuid = peripheral.identifier.uuidString
            localName = discovery.localName
            
            if discovery.ver != "" {
                versoin = discovery.ver
            }
            if discovery.mac != "" {
                adress = discovery.mac
            }
            
            RSSI = discovery.RSSI
            
            if let info = discovery.info, let adress = discovery.mac {
                print("戒指信息")
                print("颜色：\(info.color)")
                print("类型：\(info.type)")
                print("尺寸：\(info.size)")
                
                let color = RingColorType(rawValue: info.color) ?? .unkown
                let info = RingInfo(adress: adress, color: color, size: info.size, type: info.type)
                info.save()
            }
            
            /// 
            self.isFirstConnect = false
            self.isBind = true
        }
        
        
        save()
        
    }
    
    
    /// 解除绑定
    public func unbind() {
        
        // 戒指相关信息不删除
        isBind = false
        save()
        
    }
    
    public func clear() {
        
        uuid = nil
        adress = nil
        localName = nil
        versoin = nil
        gitHash = nil
        RSSI = 0
        hide = 0
         
       save()
        
    }
 
}

extension DeviceInfo {
    
    /// 戒指颜色
    public enum RingColorType: Int, HandyJSONEnum {
        
        /// 未知颜色
        case unkown = -1
        /// 枪色
        case gun = 0
        /// 银色
        case silvery = 1
        /// 玫瑰金
        case rose = 2
        /// 金色14K
        case gold = 3
        /// 咖啡金
        case coffee = 4
        
        public var name: String {
            
            switch self {
            case .gun:
                return "device_color_gun".language
            case .silvery:
                return "device_color_sliver".language
            case .rose:
                return "device_color_rose_gold".language
            case .gold:
                return "device_color_gold".language
            case .coffee:
                return "device_color_coffee_gold".language
            default:
                return ""
            }
            
            
        }
        
        public var imageName: String {
            
            switch self {
                
            case .gun:
                return "ic_device_ring_black"
            case .silvery:
                return "ic_device_ring_silver"
            case .rose:
                return "ic_device_ring_rosegold"
            case .gold:
                return "ic_device_ring_gold"
            case .coffee:
                return "ic_device_ring_coffeegold"
                
            default:
                return "ic_device_ring_coffeegold"
            }
            
            
            
        }
        
    }
    
    
}

extension DeviceInfo {
    
    public struct RingInfo: HandyJSON {
        
        private static let userDefaultKey = "DeviceInfo.RingInfo"
        
        public var adress: String = ""
        
        public var color: RingColorType = .unkown
        public var size: Int = 0
        public var type: Int = 0
        
        public var imageURL: String?
        
        public init() {}
        
        public init(adress: String, color: RingColorType, size: Int, type: Int, imageURL: String? = nil) {
            self.adress = adress
            self.color = color
            self.size = size
            self.type = type
            self.imageURL = imageURL
        }
        
        
        public func save() {
            
            let array = UserDefaults.standard.array(forKey: Self.userDefaultKey) ?? []
            guard var infos = [RingInfo].deserialize(from: array)?.compactMap({ $0 }), var dict = self.toJSON() else {
                return
            }
            
            if let oldInfo = infos.filter({ $0.adress == self.adress }).first, let old = oldInfo.toJSON() {
                
                old.forEach { key, value in
                    
                    if !dict.keys.contains(key) {
                        dict[key] = value
                    }
                }
                
                guard let index = infos.firstIndex(where: { $0.adress == self.adress }) else { return }
                infos.remove(at: index)
    
            }
            
            guard let newInfo = RingInfo.deserialize(from: dict) else {
                return
            }
            
            infos.append(newInfo)
            print(infos)
            
            let newArray = infos.toJSON().compactMap({ $0 })
            UserDefaults.standard.set(newArray, forKey: Self.userDefaultKey)
            
        }
        
        /// 当前存储的设备信息
        /// - Returns: model
        public static func current(adress: String) -> DeviceInfo.RingInfo? {
            
            let array = UserDefaults.standard.array(forKey: Self.userDefaultKey)
            guard let infos = [RingInfo].deserialize(from: array), let info = infos.filter({ $0?.adress == adress }).first else {
                return nil
            }
            
            return info
            
        }
        
    }
    
}
